package org.csu.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.demo.common.CommonResponse;
import org.csu.demo.domain.*;
import org.csu.demo.persistence.CategoryMapper;
import org.csu.demo.persistence.InventoryMapper;
import org.csu.demo.persistence.ItemMapper;
import org.csu.demo.persistence.ProductMapper;
import org.csu.demo.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("catalogService")
public class CatalogServiceImpl implements CatalogService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private InventoryMapper inventoryMapper;

    public CommonResponse<List<Category>> findAllCategories(){
        List<Category> categories = categoryMapper.selectList(null);
        return CommonResponse.createForSuccess(categories);
    }

    public CommonResponse<List<Product>> searchProducts(String keyword){
        List<Product> products = productMapper.searchProducts("%"+keyword+"%");
        return CommonResponse.createForSuccess(products);
    }

    public CommonResponse<List<Product>> findAllProducts(){
        List<Product> products = productMapper.selectList(null);
        return CommonResponse.createForSuccess(products);
    }

    public CommonResponse<List<Item>> findAllItems(){
        List<Item> items = itemMapper.selectList(null);
        return CommonResponse.createForSuccess(items);
    }

    public CommonResponse<Category> findCategoryById(String id){
        Category category = categoryMapper.selectById(id);
        return CommonResponse.createForSuccess(category);
    }

    public CommonResponse<Product> findProductById(String id){
        Product product = productMapper.selectById(id);
        return CommonResponse.createForSuccess(product);
    }

    public CommonResponse<Item> findItemById(String id){
        Item item = itemMapper.selectById(id);
        return CommonResponse.createForSuccess(item);
    }

    public CommonResponse<List<Product>> findProductsByCategory(String id){
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category",id);
        List<Product> products = productMapper.selectList(queryWrapper);
        return CommonResponse.createForSuccess(products);
    }



    public CommonResponse<List<Item>> findItemsByProductId(String id){
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("productid",id);
        List<Item> items = itemMapper.selectList(queryWrapper);
        return CommonResponse.createForSuccess(items);
    }


    //更新商品库存
    public void updateInventoryQuantity(Map<String, Object> param) {
        try{
            Object itemIdObj = param.get("itemId");
            String itemIdValue = "";
// 检查 itemIdObj 是否为 String 类型
            if (itemIdObj instanceof String) {
                itemIdValue = (String) itemIdObj;
                // 使用 itemIdValue 进行后续操作
            }
            Object incrementObj = param.get("increment");
            Integer quantity = 0;
            if (incrementObj instanceof Integer) {
                quantity = (Integer) incrementObj;
                // 使用 incrementValue 进行后续操作
            }
            //更新的方法，可以将商品数量更新到数据库
            Inventory inventory = new Inventory();
            inventory.setQuantity(quantity);
            inventory.setItemId(itemIdValue);
            inventoryMapper.updateById(inventory);
            // 查询更新后的库存数量
            int updatedQuantity = inventoryMapper.selectById(itemIdValue).getQuantity();
            // 如果更新后的库存数量为负数，则下架商品
            if (updatedQuantity < 0) {
                offStoreItem(itemIdValue);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //下架商品
    public void offStoreItem(String itemId){
        try{
            itemMapper.deleteById(itemId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据itemId获取description
    public CommonResponse<DescVo> getDescByItemId(String itemId){
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid",itemId);
        Item item = itemMapper.selectOne(queryWrapper);
        String productId = item.getProductId();
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("productid",productId);
        Product product = productMapper.selectOne(productQueryWrapper);
        String description = product.getDescription();
        System.out.println(description);
        DescVo descVo = new DescVo();
        // 提取 src 属性中的文件名
        Pattern srcPattern = Pattern.compile("<(?:img|image)[^>]*src=['\"][^'\"]*/([^'\"]+)['\"]", Pattern.CASE_INSENSITIVE);
        Matcher srcMatcher = srcPattern.matcher(description);

        if (srcMatcher.find()) {
            String fileName = srcMatcher.group(1);
            System.out.println("图片文件名: " + fileName);
            descVo.setFileName(fileName);
        }

        // 提取 <img> 或 <image> 标签后面的紧跟文本（非标签内容）
        Pattern afterImgPattern = Pattern.compile("<(?:img|image)[^>]*>\\s*([^<]+)");
        Matcher afterImgMatcher = afterImgPattern.matcher(description);

        if (afterImgMatcher.find()) {
            String textAfterImg = afterImgMatcher.group(1).trim();
            if (!textAfterImg.isEmpty()) {
                System.out.println("描述文字: " + textAfterImg);
                descVo.setDescription(textAfterImg);
            }
        }

        // 提取其他标签内部的文字（如 <font> 等）
        Pattern innerTextPattern = Pattern.compile(">([^<>]+)<");
        Matcher innerTextMatcher = innerTextPattern.matcher(description);

        while (innerTextMatcher.find()) {
            String text = innerTextMatcher.group(1).trim();
            if (!text.isEmpty()) {
                System.out.println("标签内部文字: " + text);
                descVo.setDescription(text);
            }
        }
        return CommonResponse.createForSuccess(descVo);
    }
}
